﻿using System.Collections.Generic;
namespace YanZhiwei.DotNet2.Utilities.Common
{
    /// <summary>
    /// List帮助类
    /// </summary>
    public static class IListHelper
    {
        #region  去重复集合添加
        /// <summary>
        /// 去重复集合添加
        ///<para>参考:http://stackoverflow.com/questions/8652340/is-there-an-addunique-method-similar-to-addrange-for-alist-in-c-sharp</para> </para>
        /// </summary>
        /// <typeparam name="T">泛型</typeparam>
        /// <param name="self">本身集合</param>
        /// <param name="items">需要集合</param>
        public static void AddUnique<T>(this IList<T> self, IEnumerable<T> items)
        {
            foreach (T item in items)
            {
                if (!self.Contains(item))
                {
                    self.Add(item);
                }
            }
        }
        #endregion
        #region  转换为List
        /// <summary>
        /// 转换为List
        /// </summary>
        /// <typeparam name="T">泛型</typeparam>
        /// <param name="self">需要转换的集合</param>
        /// <returns>List</returns>
        public static List<T> ConvertToList<T>(this IEnumerable<T> self)
        {
            List<T> _toList = new List<T>(self);
            return _toList;
        }
        #endregion
        #region 集合添加
        /// <summary>
        /// 集合添加
        /// </summary>
        /// <typeparam name="T">泛型</typeparam>
        /// <param name="self">本身集合</param>
        /// <param name="list">需要添加集合</param>
        public static void AddRange<T>(this IList<T> self, IEnumerable<T> list)
        {
            ((List<T>)self).AddRange(list);
        }
        #endregion
        #region 去重复集合添加
        /// <summary>
        /// 去重复集合添加
        /// </summary>
        /// <typeparam name="T">泛型</typeparam>
        /// <param name="self">本身集合</param>
        /// <param name="items">需要添加集合</param>
        /// <param name="comparaer">IComparer</param>
        public static void AddUnique<T>(this List<T> self, IEnumerable<T> items, IComparer<T> comparaer)
        {
            self.Sort(comparaer);
            foreach (T item in items)
            {
                int _result = self.BinarySearch(item, comparaer);//搜索前需要排序
                if (_result < 0)
                    self.Add(item);
            }
        }
        #endregion
    }
}